%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% File:               marginal2.m
%
% Authors:            Sergio Ascencio and Miguel Rueda
%
% Description:        It computes predicted best responses and standard
%                     errors
%
% Language:           MATLAB R2013b (8.2.0.701) 64 Bit
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


function [UCI,LCI,pred]=marginal2(beta,betas_monte,mean_X_PRI,mean_X_PAN,mean_X_PRD,pri_pan_prd,m_h)

%saving the simulated predictions
preds=cell(2,size(betas_monte,2));
for i=1:size(betas_monte,2)
    [p_PAN,p_PRI,p_PRD]=predicted_probs2(betas_monte(:,i),mean_X_PRI,mean_X_PAN,mean_X_PRD);
    if pri_pan_prd==1
        preds{1,i}=p_PRI(:,2);
        preds{2,i}=p_PRI(:,3);
    elseif pri_pan_prd==2
        preds{1,i}=p_PAN(:,2);
        preds{2,i}=p_PAN(:,3);
    else
        preds{1,i}=p_PRD(:,2);
        preds{2,i}=p_PRD(:,3);        
    end    
end

%main prediction
[p_PAN,p_PRI,p_PRD]=predicted_probs2(beta,mean_X_PRI,mean_X_PAN,mean_X_PRD);
if pri_pan_prd==1
   pred_m=p_PRI(:,2);
   pred_h=p_PRI(:,3);
elseif pri_pan_prd==2
   pred_m=p_PAN(:,2);
   pred_h=p_PAN(:,3);
else
   pred_m=p_PRD(:,2);
   pred_h=p_PRD(:,3);    
end  

%choosing between probability of medium or high
if m_h==1
    preds=cell2mat(preds(1,:));
    pred=pred_m;
else
    preds=cell2mat(preds(2,:));
    pred=pred_h;
end

%calculating confidence intervals
s_e=std(preds,0,2);
LCI=pred+(norminv((1-0.95)/2,0,1))*s_e;
UCI=pred-(norminv((1-0.95)/2,0,1))*s_e;

end

